//
//  YuHTTPClient.m
//  HuLaQuan
//
//  Created by hok on 1/6/16.
//  Copyright © 2016 Jianghao. All rights reserved.
//

#import "YuHTTPClient.h"
#import <AFNetworking.h>
#import "XMLDictionary.h"


@interface YuHTTPClient()<NSURLConnectionDelegate>

@end

@implementation YuHTTPClient


+ (void)netWorkStatus:(void (^)(id))block
{
    /**
     AFNetworkReachabilityStatusUnknown          = -1,  // 未知
     AFNetworkReachabilityStatusNotReachable     = 0,   // 无连接
     AFNetworkReachabilityStatusReachableViaWWAN = 1,   // 3G 花钱
     AFNetworkReachabilityStatusReachableViaWiFi = 2,   // WiFi
     */
    // 如果要检测网络状态的变化,必须用检测管理器的单例的startMonitoring
    [[AFNetworkReachabilityManager sharedManager] startMonitoring];
    
    // 检测网络连接的单例,网络变化时的回调方法
    [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        //NSLog(@"%ld", status);
        block([NSString stringWithFormat:@"%d",status]);
        
    }];
}

+ (NSString *)base64EncodeString:(NSString *)string
{
    NSData *Data=[string dataUsingEncoding:NSUTF8StringEncoding];
    //进行编码
    Data =[GTMBase64 encodeData:Data];
    
    NSString *codestr=[[NSString alloc] initWithData:Data encoding:NSUTF8StringEncoding];
    return codestr;
}


+ (NSString *)base64DecodeString:(NSString *)string
{
    NSData *Data=[string dataUsingEncoding:NSUTF8StringEncoding];
    //进行编码
    Data =[GTMBase64 decodeData:Data];
    
    NSString *codestr=[[NSString alloc] initWithData:Data encoding:NSUTF8StringEncoding];
    return codestr;
}
+ (NSString *)encodeToPercentEscapeString: (NSString *) input
{
    // Encode all the reserved characters, per RFC 3986
    // (<http://www.ietf.org/rfc/rfc3986.txt>)
    NSString *outputStr = (NSString *)
    CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
                                            (CFStringRef)input,
                                            NULL,
                                            (CFStringRef)@"!*'();:@&=+$,/?%#[]",
                                            kCFStringEncodingUTF8));
    return outputStr;
}
+ (void)XMLDataWithUrl:(NSString *)url parameters:(NSString *)parameter success:(void (^)(BOOL isSuccess, id item))block
{

    
    NSURL *urlX = [NSURL URLWithString:url];
    
    NSString *post=@"postData";
    
  //  NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
  /*
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:urlX];
    [request setHTTPMethod:@"POST"];
    [request setValue:@"text/xml" forHTTPHeaderField:@"Content-Type"];
    NSString *urlString = [YuHTTPClient encodeToPercentEscapeString:parameter];
    NSData * bodyData = [urlString dataUsingEncoding:NSUTF8StringEncoding];
    
   
    [request setHTTPBody:bodyData];


    [request setValue:[NSString stringWithFormat:@"%ld",bodyData.length] forHTTPHeaderField:@"Content-Length"];
    [request setTimeoutInterval:10.0];
    
    NSOperationQueue *queue = [[NSOperationQueue alloc]init];
    [NSURLConnection sendAsynchronousRequest:request
                                       queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error){
                                           if (error) {
                                               NSLog(@"Httperror:%@%d", error.localizedDescription,error.code);
                                           }else{
                                               
                                               NSInteger responseCode = [(NSHTTPURLResponse *)response statusCode];
                                               
                                               NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                                               
                                               NSLog(@"HttpResponseCode:%d", responseCode);
                                               NSLog(@"HttpResponseBody %@",responseString);
                                               
                                               NSArray *arr = [responseString componentsSeparatedByString:@"|"];
                                               NSString *string1 = arr[2];
                                               NSLog(@"%@",string1);
                                               NSString *string = [YuHTTPClient base64DecodeString:arr[2]];
                                               NSLog(@"%@",string);
                                               if(block)
                                               {
                                                   block(NO,string);
                                               }
                                           }
                                       }];
    
    */

//    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];

    manager.responseSerializer = [AFHTTPResponseSerializer serializer];

//    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/plain"];
    
    
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:urlX];
    [request setHTTPMethod:@"POST"];
    [request setValue:@"application/octet-stream" forHTTPHeaderField:@"Content-Type"];
   // NSString *urlString = [YuHTTPClient encodeToPercentEscapeString:parameter];
    NSData * bodyData = [parameter dataUsingEncoding:NSUTF8StringEncoding];
    
    
    [request setHTTPBody:bodyData];
    AFHTTPRequestOperation *operation = [manager HTTPRequestOperationWithRequest:request success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        NSString *responseString = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
        
       // NSLog(@"HttpResponseCode:%d", responseCode);
        NSLog(@"HttpResponseBody %@",responseString);
        
        NSArray *arr = [responseString componentsSeparatedByString:@"|"];
        
        if([[arr firstObject] isEqualToString:@"1"]){
            if(block)
            {
                block(YES,arr);
            }
        }else{
            NSString *string = [YuHTTPClient base64DecodeString:[arr lastObject]];
            if (block) {
                block(NO,string);
            }
        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        //NSLog(@"%@", error);
        if (block) {
            block(NO, error);
        }
    }];
    
    [manager.operationQueue addOperation:operation];
    

}

//FM
+ (void)XMLFMDataWithUrl:(NSString *)url parameters:(NSString *)parameter success:(void (^)(BOOL isSuccess, id item))block
{
  //  NSString *urlString = [YuHTTPClient encodeToPercentEscapeString:url];
    
    NSLog(@"%@ %@",url,parameter);
    NSURL *urlX = [NSURL URLWithString:url];
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:urlX];
    
    [request setHTTPMethod:@"POST"];
    //text
    [request setValue:@"text/xml" forHTTPHeaderField:@"Content-Type"];
    NSData * bodyData = [parameter dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:bodyData];
    
    
    AFHTTPRequestOperation *operation = [manager HTTPRequestOperationWithRequest:request success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        NSString *responseString = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
        
        NSLog(@"HttpResponseBody %@",responseString);
        NSXMLParser *parser = [[NSXMLParser alloc] initWithData:responseObject];
        ////                   //这里使用了第三方框架 XMLDictionary，他本身继承并实现 NSXMLParserDelegate 委托代理协议，对数据进行遍历处理
       // NSLog(@"%@",[NSDictionary dictionaryWithXMLParser:parser]);
        
        NSDictionary *resultDic = [[NSDictionary alloc] initWithDictionary:[NSDictionary dictionaryWithXMLParser:parser]];
        NSString *response = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
        NSLog(@" --- %@ --- ",response);
   
        if(block)
        {
            NSLog(@"~~~~~~~~ %@ %@  %@",resultDic,[resultDic objectForKey:@"node"],[resultDic objectForKey:@"_state"]);
            
            if ([resultDic[@"_state"] isEqualToString:@"true"]) {
                NSLog(@"turereureur te");
                
                block(YES,resultDic[@"node"]);

                
            }
            else{
                
                block(NO,resultDic[@"node"][@"errormessage"]);
            }
            
        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        //NSLog(@"%@", error);
        if (block) {
            
            block(NO, error);
        }
    }];
    
    [manager.operationQueue addOperation:operation];
}


//progressData
+(void)DownloadDataWithUrl:(NSString *)url parameters:(NSString *)parameter success:(void (^)(BOOL isSuccess, id item))block progress:(void (^)(float prog))progressBlock
{
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    [configuration setTimeoutIntervalForRequest:50];
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
    
    
    
    [manager setDownloadTaskDidWriteDataBlock:^(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, int64_t bytesWritten, int64_t totalBytesWritten, int64_t totalBytesExpectedToWrite) {
        
        NSLog(@"Progress… %lld", totalBytesWritten);
        float progressFloat = (float)totalBytesWritten/totalBytesExpectedToWrite;
        NSLog(@"%f",progressFloat);
       // NSString *progress = [NSString stringWithFormat:@"%d%%",(int)(progressFloat *100)] ;
        if (progressBlock) {
            progressBlock(progressFloat);
        }
    }];
    
    NSURL *URL = [NSURL URLWithString:[url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    NSURLRequest *request = [NSURLRequest requestWithURL:URL];
  //  [request setTimeoutInterval:50];
    
    
    
    NSProgress *progress;
    
    NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request  progress:&progress destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
        
        NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
        return [documentsDirectoryURL URLByAppendingPathComponent:[response suggestedFilename]];
        
    } completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
        
        //传出去的数据
        if (error) {
            block(NO,error);
        }
        else
        {
            
            NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
            NSString *documentsDirectory=[paths objectAtIndex:0];//Documents目录
            
            NSString *saveFilePath = [documentsDirectory stringByAppendingPathComponent:[url lastPathComponent]];
            NSLog(@"File downloaded to: %@ %@", filePath,saveFilePath);
            NSString *file = [filePath path];
        
             block(YES,file);
            
        }
       

        
    }];
    
    [downloadTask resume];
    
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(nonnull NSError *)error
{
    NSLog(@"%@",error);
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    
    NSString *responseText = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    
    NSLog(@"%@", responseText);
}
@end
